package net.uman.framework.jms;

import java.util.Map;

import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.Session;

import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;

/**
 * JMS消息生产者.
 * 
 * 使用jmsTemplate将String消息分别发送到queue与topic.
 * 
 * @author calvin
 */
public class AdvancedNotifyMessageProducer {

	private JmsTemplate jmsTemplate;
	private Destination notifyQueue;
	private Destination notifyTopic;

	public void sendQueue(final String message) {
		sendMessage(message, notifyQueue);
	}

	public void sendTopic(final String message) {
		sendMessage(message, notifyTopic);
	}

	public void sendQueue(final Map message) {
		sendMessage(message, notifyQueue);
	}

	public void sendTopic(final Map message) {
		sendMessage(message, notifyTopic);
	}
	
	/**
	 * 使用jmsTemplate的send/MessageCreator()发送Map类型的消息并在Message中附加属性用于消息过滤.
	 */
	private void sendMessage(final String msg, Destination destination) {
		jmsTemplate.send(destination, new MessageCreator() {
			public Message createMessage(Session session) throws JMSException {

				MapMessage message = session.createMapMessage();
				message.setString("message", msg);
				//message.setStringProperty("objectType", "user");

				System.out.println("sendMessage("+msg);
				
				return message;
			}
		});
	}

	private void sendMessage(final Map msg, Destination destination) {
		jmsTemplate.convertAndSend(destination, msg);
	}

	public void setJmsTemplate(JmsTemplate jmsTemplate) {
		this.jmsTemplate = jmsTemplate;
	}

	public void setNotifyQueue(Destination notifyQueue) {
		this.notifyQueue = notifyQueue;
	}

	public void setNotifyTopic(Destination nodifyTopic) {
		this.notifyTopic = nodifyTopic;
	}
}
